import { mapState } from 'vuex'
import { getIsShow, recoverUp } from '@/api/commondity/index'
export default {
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    }),
    tableHeight () {
      let height = this.tableData.length > 5 ? 520 : 0
      return height
    }
  },
  watch: {
    modalShow (status) {
      if (!status) {
        this.$refs.formInline.resetFields()
        this.activityEndOptions = {}
        this.activityStartOptions = {}
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.shopId !== to.params.id) {
        vm.shopId = to.params.id
        vm.transmit.shopId = to.params.id
        vm.reset()
      }
    })
  },
  data () {
    return {
      shopId: '',
      loading: false,
      drawShow: false,
      modalShow: false,
      defaultUrl: require('@/assets/images/default.png'),
      channelGoodsId: '',
      activityStartOptions: {},
      activityEndOptions: {},
      tableData: [],
      searchName: '',
      status: '1',
      saleType: '1',
      pageObj: {
        searchName: '',
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      saleList: [
        { value: '1', label: '已上架' },
        { value: '2', label: '已下架' }
      ],
      statusList: [
        { value: '1', label: '已显示' },
        { value: '0', label: '已隐藏' }
      ],
      formInline: {
        goodsName: '',
        upTime: '',
        downTime: ''
      },
      ruleInline: {
        upTime: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formInline.upTime).getTime()) {
              callback(new Error('请选择上架时间'))
            } else if (new Date(this.formInline.upTime).getTime() > new Date(this.formInline.downTime).getTime() || new Date(this.formInline.upTime).getTime() === new Date(this.formInline.downTime).getTime()) {
              callback(new Error('上架时间要小于下架时间'))
            } else {
              callback()
            }
          }
        },
        downTime: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formInline.downTime).getTime()) {
              callback(new Error('请选择下架时间'))
            } else if (new Date(this.formInline.upTime).getTime() > new Date(this.formInline.downTime).getTime() || new Date(this.formInline.upTime).getTime() === new Date(this.formInline.downTime).getTime()) {
              callback(new Error('下架时间要大于上架时间'))
            } else if (new Date().getTime() > new Date(this.formInline.downTime).getTime()) {
              callback(new Error('下架时间要大于当前系统时间'))
            } else {
              callback()
            }
          }
        }
      },
      columns: [
        {
          title: '商品主图',
          slot: 'imgUrl'
        },
        {
          title: '商品编码',
          key: 'skuId'
        },
        {
          title: '商品名称',
          key: 'skuName'
        },
        {
          title: this.$route.name === 'lie_list' ? '休闲项分类' : this.$route.name === 'server_list' ? '服务分类' : this.$route.name === 'gamecard_list' ? '游戏卡分类' : '新项目分类',
          key: 'goodsTypeName'
        },
        {
          title: '平台价(元)',
          slot: 'standardPrice'
        },
        {
          title: '上下架时间',
          slot: 'time'
        },
        {
          title: '状态',
          slot: 'goodsStatus'
        },
        // {
        //   title: '状态',
        //   slot: 'status'
        // },
        {
          title: '操作时间',
          key: 'operatedAt'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ]
    }
  },
  methods: {
    doSearch () {
      this.pageObj.pageIndex = 1
      this.pageObj.searchName = this.searchName
      this.getData()
    },
    reset () {
      this.saleType = '1'
      this.status = ''
      this.searchName = ''
      this.pageObj.searchName = ''
      this.pageObj.pageIndex = 1
      this.pageObj.pageSize = 20
      this.getData()
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    activityStartChange (time) {
      this.formInline.upTime = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time.split(' ')[0]).getTime() - 24 * 3600 * 1000
        }
      }
    },
    activityEndChange (time) {
      this.formInline.downTime = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    displayDraw () {
      this.drawShow = true
    },
    closeDraw (data) {
      this.drawShow = data
    },
    sureSelect (data) {
      if (data) {
        this.getData()
      }
    },
    againUp (row) {
      this.modalShow = true
      this.formInline.goodsName = row.skuName
      this.channelGoodsId = row.channelGoodsId
    },
    onSure () {
      this.$refs.formInline.validate(valid => {
        if (valid) {
          let data = {
            channelGoodsId: this.channelGoodsId,
            listingAt: this.formInline.upTime,
            delistingAt: this.formInline.downTime,
            creator: this.userId,
            creatorName: this.userName
          }
          this.recoverUp(data)
        }
      })
    },
    // 重新上架
    recoverUp (data) {
      recoverUp(data).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('重新上架成功！')
          this.modalShow = false
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    handleFuc (result) {
      this.tableData = result.data.goods || []
      this.pageObj.total = result.data.total
      if (result.data.goods.length / this.pageObj.pageSize === 0) {
        if (this.pageObj.pageIndex > 1) {
          this.pageObj.pageIndex--
          this.getData()
        }
      }
      if (this.tableData.length > 0) {
        this.tableData.forEach(ele => {
          ele.goodsTypeName = []
          ele.isShow = !!Number(ele.isShow)
          if (ele.goodsKindList.length > 0) {
            ele.goodsKindList.forEach(item => {
              ele.goodsTypeName.push(item.typeName)
            })
          }
          ele.goodsTypeName = ele.goodsTypeName.join('-')
        })
      }
    },
    cancelDown (row) {},
    sureDown (row) {
      let data = {
        channelGoodsId: row.channelGoodsId,
        listingType: 2
      }
      this.getStatus(data)
    },
    changeStatus (row) {
      let data = {
        channelGoodsId: row.channelGoodsId,
        showType: row.isShow ? 1 : 0
      }
      this.getStatus(data)
    },
    // 显示与隐藏
    getStatus (data) {
      getIsShow({
        merchantId: this.merchantId,
        updater: this.userId,
        updaterName: this.userName,
        ...data
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          if (data.listingType) {
            this.$Message.success('下架成功！')
          } else {
            this.$Message.success('更新成功！')
          }
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.shopId = this.$route.params.id
    this.getData()
  }
}
